package mvc.authentication;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mvc.model.User;
import mvc.model.UserInformation;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping(value = "/authentication", method = RequestMethod.POST)
public class UserAuth {

	@RequestMapping(value = "/login.auth", method = RequestMethod.POST)
	public void login(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		User user = new User();
		user.setUsername(request.getParameter("usernameLoginField"));
		user.setPassword(request.getParameter("passwordLoginField"));
		user.setRole("ROOT");
		
		UserInformation userInformation = new UserInformation();
		userInformation.setName("Luca");
		userInformation.setSurname("Zenobi");
		userInformation.setRegisterDate(new Date());
		
		user.setUserInformation(userInformation);

		if (user.getUsername().equals("root") && user.getPassword().equals("pass")) {
			request.getSession(true).setAttribute("logged", true);
			request.getSession().setAttribute("loginInfoMessage", null);
			request.getSession().setAttribute("user", user);
			response.sendRedirect("/redru-manager/jsp/home.jsp");
		} else {
			request.getSession().setAttribute("loginInfoMessage", "Wrong username or password.");
			response.sendRedirect("/redru-manager/index.jsp");
		}
	}

	@RequestMapping(value = "/logout.auth", method = RequestMethod.POST)
	public void logout(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		request.getSession().invalidate();
		request.getSession(true).setAttribute("logged", false);
		request.getSession().setAttribute("loginInfoMessage", "Logout executed.");
		
		response.sendRedirect("/redru-manager/index.jsp");
	}

}